package com.jus.player.activity.home;

import static com.jus.player.api.OkHttpHelper._DATA;
import static com.jus.player.api.OkHttpHelper._RECORD;
import static com.jus.player.config.AppConfig.KEY_CATEGORY_ID;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson2.JSONObject;
import com.google.android.gms.common.util.CollectionUtils;
import com.jus.player.R;
import com.jus.player.activity.BaseActivity;
import com.jus.player.adapter.home.SearchAdapter;
import com.jus.player.adapter.home.SearchHotAdapter;
import com.jus.player.api.ApiConfig;
import com.jus.player.api.OkHttpHelper;
import com.jus.player.entity.VideoEntity;
import com.jus.player.util.CommonUtils;
import com.jus.player.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SearchActivity extends BaseActivity {

    private final List<VideoEntity> videoList = new ArrayList<>();
    private final List<VideoEntity> hotVideos = new ArrayList<>();
    private EditText etVideoName;
    private TextView btnSearch;
    private RecyclerView recyclerView;
    private RecyclerView recyclerViewHot;
    private SearchAdapter searchAdapter;
    private SearchHotAdapter searchHotAdapter;
    private final Handler handler = new Handler(); // 用于延迟搜索
    private Runnable searchRunnable; // 延迟搜索任务
    private Long categoryId;

    private View emptyStateView;

    @Override
    protected int initLayout() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {
        //返回
        ImageView searchBack = findViewById(R.id.search_back);
        searchBack.setOnClickListener(view -> finish());

        etVideoName = findViewById(R.id.et_video_name);
        btnSearch = findViewById(R.id.btn_search);
        recyclerView = findViewById(R.id.recyclerView_search);
        recyclerViewHot = findViewById(R.id.recyclerView_search_hot);
        //空页面
        emptyStateView = findViewById(R.id.layoutEmptyState);
    }

    @Override
    protected void initData() {
        categoryId = getIntent().getLongExtra(KEY_CATEGORY_ID, 0);
        //搜索视频
        btnSearch.setOnClickListener(
                view -> searchVideoByName(etVideoName.getText().toString().trim(), categoryId)
        );
        // 设置输入监听
        etVideoName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                // 输入内容变化前的回调
            }

            // 输入内容变化时的回调
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                // 移除之前的延迟任务
                handler.removeCallbacks(searchRunnable);
                // 创建新的延迟任务
                searchRunnable = new Runnable() {
                    @Override
                    public void run() {
                        String keyword = etVideoName.getText().toString().trim();
                        searchVideoByName(keyword, categoryId); // 触发搜索
                    }
                };
                // 延迟 1 秒执行搜索
                handler.postDelayed(searchRunnable, 500);
            }

            @Override
            public void afterTextChanged(Editable editable) {
                // 输入内容变化后的回调
            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        searchAdapter = new SearchAdapter();
        searchAdapter.setVideoList(videoList);
        recyclerView.setAdapter(searchAdapter);
        //搜索热门视频
        getSearchHotVideos();
        recyclerViewHot.setLayoutManager(new LinearLayoutManager(this,
                LinearLayoutManager.HORIZONTAL, false));
        searchHotAdapter = new SearchHotAdapter();
        searchHotAdapter.setVideoList(hotVideos);
        recyclerViewHot.setAdapter(searchHotAdapter);
    }

    private void searchVideoByName(String videoName, Long categoryId) {
        videoList.clear();
        recyclerView.setVisibility(View.VISIBLE);
        emptyStateView.setVisibility(View.GONE);
        if (StringUtils.isEmpty(videoName)) {
            runOnUiThread(() -> searchAdapter.notifyDataSetChanged());
            CommonUtils.showToastPos(this, getString(R.string.hint_input_name), 500, true);
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("title", videoName);
        params.put("categoryId", categoryId + "");
        OkHttpHelper.getInstance(this).getAsync(ApiConfig.SEARCH_VIDEO_BY_TITLE, params,
                new OkHttpHelper.HttpCallback() {
                    @Override
                    public void onSuccess(String res) {
                        JSONObject jo = JSONObject.parseObject(res);
                        List<VideoEntity> resList = jo.getList(_DATA, VideoEntity.class);
                        for (VideoEntity v : resList) {
                            List<JSONObject> typeList = v.getTypeList();
                            if (!CollectionUtils.isEmpty(typeList)) {
                                for (JSONObject t : typeList) {
                                    if (t.getInteger("type") == 0) {
                                        v.setLastEpisode(t.getInteger("lastEpisode"));
                                    }
                                }
                            }
                        }
                        if (resList == null || resList.isEmpty()) {
                            runOnUiThread(() -> {
                                // 没有数据时显示空状态页面，隐藏列表
                                recyclerView.setVisibility(View.GONE);
                                emptyStateView.setVisibility(View.VISIBLE);
                            });
                        }
                        videoList.addAll(resList);
                        runOnUiThread(() -> searchAdapter.notifyDataSetChanged());
                    }

                    @Override
                    public void onFailure(OkHttpHelper.HttpException e) {
                        CommonUtils.showToastAsync(SearchActivity.this, e.getMessage());
                    }
                });
    }


    /**
     * 查询搜索热门视频
     */
    private void getSearchHotVideos() {

        Map<String, String> map = new HashMap<>();
        map.put("pageNo", "1");
        map.put("pageSize", ApiConfig.PAGE_30_SIZE + "");
        map.put("categoryId", "1");
        OkHttpHelper.getInstance(this).getAsync(ApiConfig.VIDEO_LIST, map,
                new OkHttpHelper.HttpCallback() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void onSuccess(String res) {
                        JSONObject jo = JSONObject.parseObject(res);
                        JSONObject pageJo = jo.getJSONObject(_DATA);
                        List<VideoEntity> resList = pageJo.getList(_RECORD, VideoEntity.class);
                        if (resList == null || resList.isEmpty()) {
                            return;
                        }
                        for (VideoEntity v : resList) {
                            List<JSONObject> typeList = v.getTypeList();
                            if (!CollectionUtils.isEmpty(typeList)) {
                                for (JSONObject t : typeList) {
                                    if (t.getInteger("type") == 0) {
                                        v.setLastEpisode(t.getInteger("lastEpisode"));
                                    }
                                }
                            }
                        }
                        hotVideos.clear();
                        hotVideos.addAll(resList);
                        runOnUiThread(() -> searchHotAdapter.notifyDataSetChanged());
                    }

                    @Override
                    public void onFailure(OkHttpHelper.HttpException e) {
                        CommonUtils.showToastAsync(SearchActivity.this, e.getMessage());
                    }
                });

    }

    @Override
    protected void onResume() {
        super.onResume();
        getWindow().setStatusBarColor(Color.WHITE);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        );
    }

    @Override
    protected void onPause() {
        super.onPause();
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        );
    }
}